import { toJS } from 'mobx'
import { observer } from 'mobx-react-lite'
import { useRef } from 'react'
import { useEffect, useState } from 'react'
import { useLocalStorage } from '../../hooks'
import { useStore } from '../../store'
import './index.css'

function Task() {
  const TODO_KEY = 'TODO_KEY'
  const [keyword, setKeyword] = useState('')
  const { taskStore } = useStore()
  const inputRef = useRef([])
  const [todoData, setTodoData] = useLocalStorage(TODO_KEY)

  // 初始化缓存数据
  useEffect(() => {
    taskStore.init(todoData)
  }, [])

  // referance: https://dev.to/stephane/how-to-make-sure-useeffect-catches-array-changes-fm3
  useEffect(() => {
    setTodoData(toJS(taskStore.list))
  }, [JSON.stringify(taskStore.list)]) // 直接监听数组，不生效，需要转换

  const changeHandler = (id) => {
    taskStore.checkTask(id)
  }

  const delHandler = (id) => {
    taskStore.delTask(id)
  }

  const inputChange = (e) => {
    setKeyword(e.target.value)
  }

  const entryHandler = (e) => {
    let data = keyword.trim()
    if (e.keyCode === 13 && data) {
      taskStore.addTask(data)
      setKeyword('')
    }
  }

  const unLockChange = (id, type, e) => {
    if (type) {
      console.log(inputRef.current[id])
      inputRef.current[id].focus()
    }
    taskStore.unLockChange(id, type)
  }

  const modifiedInput = (id, e) => {
    let value = e.target.value.trim()
    taskStore.modifiedTask(id, value)
  }

  const modifiedInputEntry = (id, e) => {
    let value = e.currentTarget.value.trim()
    if (e.keyCode === 13 && value) {
      taskStore.modifiedTask(id, value)
      inputRef.current[id].blur()
    }
  }

  return (
    <div className="todo-wrapper">
      <section className="todoapp">
        <section className="main">
          <input
            className="new-todo"
            autoFocus
            autoComplete="off"
            placeholder="What needs to be done?"
            value={keyword}
            onChange={inputChange}
            onKeyUp={entryHandler}
          />
          <ul className="todo-list">
            {taskStore.list.map((item, index) => (
              <li className="todo" key={item.id}>
                <div className="view">
                  <input
                    className="toggle"
                    type="checkbox"
                    checked={item.isDone}
                    onChange={() => changeHandler(item.id)}
                  />
                  <label className="label" htmlFor={item.id}>
                    <input
                      className="label-value"
                      id={item.id}
                      value={item.name}
                      readOnly={item.isLock}
                      onChange={(e) => modifiedInput(item.id, e)}
                      onDoubleClick={(e) => unLockChange(item.id, true, e)}
                      onBlur={() => unLockChange(item.id, false)}
                      onKeyUp={(e) => modifiedInputEntry(item.id, e)}
                      ref={(dom) => {
                        if (dom) {
                          inputRef.current[item.id] = dom
                        }
                      }}
                    ></input>
                  </label>
                  <button
                    className="destroy"
                    onClick={() => delHandler(item.id)}
                  ></button>
                </div>
              </li>
            ))}
          </ul>
        </section>
        <footer className="footer">
          <span className="todo-count">
            任务总数: {taskStore.taskTotal} 已完成: {taskStore.taskFinisedCount}
          </span>
        </footer>
      </section>
    </div>
  )
}

export default observer(Task)
